<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog storage-product-edit-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="title"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <p slot="title">
        {{
          readOnly && editId
            ? "查看危化品信息"
            : editId
            ? "编辑危化品信息"
            : "新增危化品信息"
        }}
      </p>
      <el-divider class="el-divider-specail" content-position="left"
        >基础信息</el-divider
      >
      <el-form
        ref="formData1"
        :model="formData"
        :rules="formDataRules"
        status-icon
        label-width="150px"
      >
        <el-row>
          <el-col v-if="readOnly || editId" :span="24">
            <el-form-item label="编号">
              <el-input
                v-model="formData.productNum"
                placeholder="请输入编号"
                :disabled="true"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="name" :error="errorMsg.name">
              <el-input
                v-model="formData.name"
                placeholder="请输入产品名称"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="别名" prop="alias" :error="errorMsg.alias">
              <el-input
                v-model="formData.alias"
                placeholder="请输入别名"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="分类"
              prop="classOneId"
              :error="errorMsg.classOneId"
            >
              <BaseTreeSelect
                v-model="formData.classOneId"
                :tree-data="categoryTree"
                placeholder="请选择分类"
                :disabled="readOnly || editId != ''"
                @node-click="handleNodeClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="生产商"
              prop="manufacturerName"
              :error="errorMsg.manufacturerName"
            >
              <el-input
                v-model="formData.manufacturerName"
                placeholder="请输入生产商"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="生产商地址"
              prop="manufacturerAddress"
              :error="errorMsg.manufacturerAddress"
            >
              <el-input
                v-model="formData.manufacturerAddress"
                placeholder="请输入生产商地址"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="生产商电话"
              prop="manufacturerMobile"
              :error="errorMsg.manufacturerMobile"
            >
              <el-input
                v-model="formData.manufacturerMobile"
                placeholder="请输入生产商电话"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="CAS号" prop="casNum" :error="errorMsg.casNum">
              <el-input
                v-model="formData.casNum"
                placeholder="请输入CAS号"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="形态"
              prop="morphologyCode"
              :error="errorMsg.morphologyCode"
            >
              <el-select
                v-model="formData.morphologyCode"
                placeholder="请选择形态"
                :disabled="readOnly"
              >
                <el-option
                  v-for="item in morphologyTypeData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="型号规格"
              prop="specifications"
              :error="errorMsg.specifications"
            >
              <el-input
                v-model="formData.specifications"
                placeholder="请输入型号规格"
                :disabled="readOnly"
                autocomplete="off"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="包装单位"
              prop="unitCode"
              :error="errorMsg.unitCode"
            >
              <el-select
                v-model="formData.unitCode"
                placeholder="请选择包装单位"
                :disabled="readOnly"
              >
                <el-option
                  v-for="item in unitCodeTypeData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="净重（克）"
              prop="netWeight"
              :error="errorMsg.netWeight"
            >
              <el-input
                v-model="formData.netWeight"
                placeholder="请输入净重（克）"
                :disabled="readOnly"
                autocomplete="off"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="毛重（克）"
              prop="roughWeight"
              :error="errorMsg.roughWeight"
            >
              <el-input
                v-model="formData.roughWeight"
                placeholder="请输入毛重（克）"
                :disabled="readOnly"
                autocomplete="off"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="存储条件"
              prop="storageConditionCode"
              :error="errorMsg.storageConditionCode"
            >
              <el-select
                v-model="formData.storageConditionCode"
                placeholder="请选择存储条件"
                :disabled="readOnly"
              >
                <el-option
                  v-for="item in storageConditionCodeTypeData"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储温度区间（℃）" prop="temperatureLower">
              <el-input
                v-model="formData.temperatureLower"
                placeholder="请填写温度下限"
                autocomplete="off"
                type="number"
                style="width: 48%; float: left"
                :disabled="readOnly"
              ></el-input>
              -
              <el-form-item
                prop="temperatureUpper"
                style="float: right; width: 48%; margin-bottom: 0px"
              >
                <el-input
                  v-model="formData.temperatureUpper"
                  placeholder="请填写温度上限"
                  autocomplete="off"
                  type="number"
                  style="width: 100%; float: right"
                  :disabled="readOnly"
                ></el-input>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="存储湿度区间（%）" prop="humidnessLower">
              <el-input
                v-model="formData.humidnessLower"
                placeholder="请填写湿度下限"
                autocomplete="off"
                type="number"
                min="0"
                style="width: 48%; float: left"
                :disabled="readOnly"
              ></el-input>
              -
              <el-form-item
                prop="humidnessUpper"
                style="float: right; width: 48%; margin-bottom: 0px"
              >
                <el-input
                  v-model="formData.humidnessUpper"
                  placeholder="请填写湿度上限"
                  autocomplete="off"
                  type="number"
                  min="0"
                  style="width: 100%; float: right"
                  :disabled="readOnly"
                ></el-input>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="质保期"
              prop="warrantyPeriod"
              :error="errorMsg.warrantyPeriod"
            >
              <el-input
                v-model="formData.warrantyPeriod"
                autocomplete="off"
                type="number"
                min="0"
                placeholder="请输入质保期"
                style="width: 48%; float: left"
                :disabled="readOnly"
              ></el-input>
              <el-select
                v-model="formData.warrantyPeriodUnit"
                placeholder="请选择"
                :disabled="readOnly"
                style="width: 48%; float: right"
              >
                <el-option label="年" value="年" />
                <el-option label="月" value="月" />
                <el-option label="日" value="日" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="库存下限"
              prop="repertoryLower"
              :error="errorMsg.repertoryLower"
            >
              <el-input
                v-model="formData.repertoryLower"
                autocomplete="off"
                placeholder="请输入库存下限"
                type="number"
                min="0"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="库存上限"
              prop="repertoryUpper"
              :error="errorMsg.repertoryUpper"
            >
              <el-input
                v-model="formData.repertoryUpper"
                autocomplete="off"
                placeholder="请输入库存上限"
                type="number"
                min="0"
                :disabled="readOnly"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="危险特性"
              prop="hazardousCharacteristics"
              :error="errorMsg.hazardousCharacteristics"
            >
              <el-input
                v-model="formData.hazardousCharacteristics"
                type="textarea"
                placeholder="请输入危险特性"
                :rows="3"
                autocomplete="off"
                :disabled="readOnly"
                maxlength="5000"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="应急救援"
              prop="emergencyRescue"
              :error="errorMsg.emergencyRescue"
            >
              <el-input
                v-model="formData.emergencyRescue"
                type="textarea"
                placeholder="请输入应急救援"
                :rows="3"
                autocomplete="off"
                :disabled="readOnly"
                maxlength="5000"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="安全防护"
              prop="safetyProtection"
              :error="errorMsg.safetyProtection"
            >
              <el-input
                v-model="formData.safetyProtection"
                type="textarea"
                placeholder="请输入安全防护"
                :rows="3"
                autocomplete="off"
                :disabled="readOnly"
                maxlength="5000"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="储运要求"
              prop="storeageConditions"
              :error="errorMsg.storeageConditions"
            >
              <el-input
                v-model="formData.storeageConditions"
                type="textarea"
                placeholder="请输入储运要求"
                :rows="3"
                autocomplete="off"
                :disabled="readOnly"
                maxlength="5000"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" :error="errorMsg.remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="3"
                autocomplete="off"
                :disabled="readOnly"
                maxlength="5000"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-collapse v-model="activeName">
        <el-collapse-item title="图片" name="1">
          <template>
            <el-form
              ref="formData2"
              v-loading="formLoading"
              :model="formData"
              :rules="formDataRules"
              label-width="130px"
              class="base-pipeline-layout system-customer-form"
            >
              <el-form-item label="图片" prop="imageUrl">
                <el-upload
                  ref="uploadImg"
                  v-model="formData.imageUrl"
                  action
                  :headers="headers"
                  :disabled="readOnly"
                  :accept="acceptImg"
                  :show-file-list="showImg"
                  :show-upload-list="showImg"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="removeImg"
                  :on-change="uploadImg"
                  :auto-upload="false"
                  :file-list="imgList"
                >
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">
                    请上传大小在5M以内， 格式在jpg，jpeg，png的图片，仅限上传1张
                  </div>
                </el-upload>
              </el-form-item>
            </el-form>
          </template>
        </el-collapse-item>
        <el-collapse-item title="附件" name="2">
          <template>
            <div class="chioseFileDiv">
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-paperclip"
                type="primary"
                @click="choiseFile()"
                >点击上传</el-button
              >
              <p>
                请上传类型为：pdf、doc、docx、xls、xlsx、zip、rar、apk；
                <br />单个文件大小不超过10M，上传总数不超过10个
              </p>
              <el-upload
                ref="upload"
                class="base-upload"
                name="FilePath"
                :multiple="true"
                action
                :headers="headers"
                :show-file-list="false"
                :show-upload-list="false"
                :accept="acceptFile"
                :disabled="readOnly"
                :on-remove="handleRemove"
                :on-change="uploadFile"
                :auto-upload="false"
                :file-list="fileList"
              ></el-upload>
            </div>
            <div class="chioseFileTable">
              <el-table
                ref="table"
                :data="formData.fileList"
                :header-cell-style="{ height: '50px' }"
                :cell-style="{ height: '50px' }"
                style="width: 100%"
              >
                <el-table-column prop="originalName" label="文件名称">
                  <template slot-scope="scope">
                    <span>
                      {{ scope.row.originalName }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="140">
                  <template slot-scope="scope">
                    <div class="base-table-operation">
                      <el-link
                        v-if="readOnly"
                        type="danger"
                        @click="downloadfile(scope.row)"
                        >点击下载</el-link
                      >
                      <el-link
                        v-else
                        type="danger"
                        @click="deletefile(scope.$index)"
                        >删除</el-link
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <BasePagination
                :total="pagination.total"
                :page-index="pagination.pageIndex"
                :page-size="pagination.pageSize"
                @sizeChange="sizeChange"
                @currentChange="currentChange"
              />
            </div>
          </template>
        </el-collapse-item>
      </el-collapse>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button v-if="!readOnly" type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button v-if="!readOnly" @click="cancel">取 消</el-button>
        <el-button v-if="readOnly" @click="cancel">返 回</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from "../../../api/System/SystemDict.js";
import {
  create,
  update,
  getTreeData,
  getInfo,
} from "../../../api/Storage/StorageProduct.js";
import { formatData, formdataify } from "../../../utils/index";
import { getToken } from "../../../utils/auth";
import { GetStaticImgInfo, GetStaticFileInfo } from "@/api/Base";
export default {
  name: "StorageProductEdit",
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },
  data() {
    const self = this;
    return {
      title: "新增危化品信息",
      loading: false,
      innerDialogFormVisible: false,
      activeName: ["1", "2"],
      formData: {
        id: 0,
        classOneMarking: "11",
        name: "",
        alias: "",
        productNum: "",
        classOneId: "",
        classTwoId: "11",
        classTwoName: "11",
        classOneName: "",
        manufacturerAddress: "",
        manufacturerName: "",
        manufacturerMobile: "",
        casNum: "",
        morphologyName: "",
        morphologyCode: "",
        specifications: "",
        unitCode: "",
        unitName: "",
        netWeight: "",
        temperatureLower: "",
        temperatureUpper: "",
        warrantyPeriodUnit: "年",
        humidnessLower: "",
        humidnessUpper: "",
        repertoryLower: "",
        repertoryUpper: "",
        hazardousCharacteristics: "",
        emergencyRescue: "",
        safetyProtection: "",
        storeageConditions: "",
        remark: "",
        imageUrl: "",
        status: "",
        roughWeight: "",
        warrantyPeriod: "",
        storageConditionCode: "",
        storageConditionName: "",
        isException: "",
        fileList: [],
      },
      formDataRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        classOneId: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        morphologyCode: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        specifications: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        unitCode: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        netWeight: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveFloatNumber,
          },
          {
            validator(rule, value, callback) {
              const roughWeight = self.formData.roughWeight;
              if (roughWeight && parseFloat(roughWeight) <= parseFloat(value)) {
                return callback(new Error("需小于毛重"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        roughWeight: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveFloatNumber,
          },
          {
            validator(rule, value, callback) {
              const netWeight = self.formData.netWeight;
              if (netWeight && parseFloat(netWeight) >= parseFloat(value)) {
                return callback(new Error("需大于净重"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        storageConditionCode: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        temperatureLower: [
          {
            validator(rule, value, callback) {
              const temperatureUpper = self.formData.temperatureUpper;
              const pattern = /^-?(0|[1-9]\d*)(\.\d{1,2})?$/;
              if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("最多支持2位小数"));
              } else if (
                temperatureUpper &&
                parseFloat(temperatureUpper) <= parseFloat(value)
              ) {
                return callback(new Error("需小于存储温度上限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        temperatureUpper: [
          {
            validator(rule, value, callback) {
              const temperatureLower = self.formData.temperatureLower;
              const pattern = /^-?(0|[1-9]\d*)(\.\d{1,2})?$/;
              if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("最多支持2位小数"));
              } else if (
                temperatureLower &&
                parseFloat(temperatureLower) >= parseFloat(value)
              ) {
                return callback(new Error("需大于存储温度下限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        humidnessLower: [
          {
            validator(rule, value, callback) {
              const humidnessUpper = self.formData.humidnessUpper;
              const pattern = /^-?(0|[1-9]\d*)(\.\d{1,2})?$/;
              if (value && value !== "" && parseFloat(value) < 0) {
                return callback(new Error("必须大于0"));
              } else if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("最多支持2位小数"));
              }
              if (
                humidnessUpper &&
                parseFloat(humidnessUpper) <= parseFloat(value)
              ) {
                return callback(new Error("需小于存储湿度上限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        humidnessUpper: [
          {
            validator(rule, value, callback) {
              const humidnessLower = self.formData.humidnessLower;
              const pattern = /^-?(0|[1-9]\d*)(\.\d{1,2})?$/;
              if (value && value !== "" && parseFloat(value) < 0) {
                return callback(new Error("必须大于0"));
              } else if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("最多支持2位小数"));
              }
              if (
                humidnessLower &&
                parseFloat(humidnessLower) >= parseFloat(value)
              ) {
                return callback(new Error("需大于存储湿度下限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        warrantyPeriod: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveIntegerNumber,
          },
        ],
        warrantyPeriodUnit: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        repertoryLower: [
          {
            validator(rule, value, callback) {
              const repertoryUpper = self.formData.repertoryUpper;
              const pattern = /^(0|[1-9]\d*)?$/; // 正整数的正则表达式
              if (value && value !== "" && parseFloat(value) < 0) {
                return callback(new Error("必须大于0"));
              } else if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("必须输入正整数"));
              } else if (
                repertoryUpper &&
                parseFloat(repertoryUpper) <= parseFloat(value)
              ) {
                return callback(new Error("需小于库存上限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        repertoryUpper: [
          {
            validator(rule, value, callback) {
              const repertoryLower = self.formData.repertoryLower;
              const pattern = /^(0|[1-9]\d*)?$/; // 正整数的正则表达式
              if (value && value !== "" && parseFloat(value) < 0) {
                return callback(new Error("必须大于0"));
              } else if (value && value !== "" && !pattern.test(value)) {
                return callback(new Error("必须输入正整数"));
              } else if (
                repertoryLower &&
                parseFloat(repertoryLower) >= parseFloat(value)
              ) {
                return callback(new Error("需大于库存下限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      initErrorMsg: {
        name: "",
        alias: "",
        productNum: "",
        classOneId: "",
        classTwoId: "",
        classTwoName: "",
        classOneName: "",
        manufacturerAddress: "",
        manufacturerName: "",
        manufacturerMobile: "",
        casNum: "",
        morphologyName: "",
        morphologyCode: "",
        specifications: "",
        unitCode: "",
        unitName: "",
        netWeight: "",
        temperatureLower: "",
        temperatureUpper: "",
        warrantyPeriodUnit: "",
        humidnessLower: "",
        humidnessUpper: "",
        repertoryLower: "",
        repertoryUpper: "",
        hazardousCharacteristics: "",
        emergencyRescue: "",
        safetyProtection: "",
        storeageConditions: "",
        remark: "",
        imageUrl: "",
        status: "",
        roughWeight: "",
        warrantyPeriod: "",
        storageConditionCode: "",
        storageConditionName: "",
        isException: "",
        createUserId: "",
        createUserName: "",
        updateUserId: "",
        updateUserName: "",
      },
      errorMsg: {
        name: "",
        alias: "",
        productNum: "",
        classOneId: "",
        classTwoId: "",
        classTwoName: "",
        classOneName: "",
        manufacturerAddress: "",
        manufacturerName: "",
        manufacturerMobile: "",
        casNum: "",
        morphologyName: "",
        morphologyCode: "",
        specifications: "",
        unitCode: "",
        unitName: "",
        netWeight: "",
        temperatureLower: "",
        temperatureUpper: "",
        warrantyPeriodUnit: "",
        humidnessLower: "",
        humidnessUpper: "",
        repertoryLower: "",
        repertoryUpper: "",
        hazardousCharacteristics: "",
        emergencyRescue: "",
        safetyProtection: "",
        storeageConditions: "",
        remark: "",
        imageUrl: "",
        status: "",
        roughWeight: "",
        warrantyPeriod: "",
        storageConditionCode: "",
        storageConditionName: "",
        isException: "",
        createUserId: "",
        createUserName: "",
        updateUserId: "",
        updateUserName: "",
      },
      // 危化品分类
      appId: 1000,
      categoryTree: [],
      // 形态
      morphologyTypeData: [],
      // 包装单位
      unitCodeTypeData: [],
      // 存储条件
      storageConditionCodeTypeData: [],
      // 文件上传
      headers: { Authorization: getToken() },
      // 文件集合
      showImg: false,
      imgList: [],
      fileList: [],
      uploadLoad: false,
      // 上传文件类型
      businessType: "40",
      ImgSize: 5 * 1024 * 1024,
      fileSize: 10 * 1024 * 1024,
      acceptImg: ".jpg,.jpeg,.png",
      acceptFile: ".pdf,.doc,.xls,.docx,.xlsx,.zip,.rar,.apk",
      dialogImageUrl: "",
      dialogVisible: false,
      // 表单加载状态
      formLoading: false,
      deleteTables: [],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  watch: {},
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    async init() {
      // 查询字典表
      // 形态
      getDictList({ dictCode: "StorageProduct_MorphologyCode" }).then((res) => {
        this.morphologyTypeData = res.data;
      });
      // 包装单位
      getDictList({ dictCode: "StorageProduct_UnitCode" }).then((res) => {
        this.unitCodeTypeData = res.data;
      });
      // 存储条件
      getDictList({ dictCode: "StorageProduct_StorageConditionCode" }).then(
        (res) => {
          this.storageConditionCodeTypeData = res.data;
        }
      );
      await this.getOptions();
      if (this.editId) {
        await this.getDetail();
      }
    },
    getDetail() {
      getInfo({ id: this.editId }).then((res) => {
        this.formData = res.data;
        const morphologyObj = {};
        morphologyObj.value = res.data.morphologyCode;
        morphologyObj.name = res.data.morphologyName;
        this.$set(this.formData, "morphologyCode", morphologyObj);
        const unitObj = {};
        unitObj.value = res.data.unitCode;
        unitObj.name = res.data.unitName;
        this.$set(this.formData, "unitCode", unitObj);
        const storageConditionObj = {};
        storageConditionObj.value = res.data.storageConditionCode;
        storageConditionObj.name = res.data.storageConditionName;
        this.$set(this.formData, "storageConditionCode", storageConditionObj);
        if (res.data.imageUrl !== "") {
          const imgFileObj = {};
          imgFileObj.name = "11";
          GetStaticImgInfo(res.data.imageUrl).then((res) => {
            imgFileObj.url = res.data;
            this.imgList.push(imgFileObj);
            this.showImg = true;
          });
        }
        if (res.data.fileList?.length > 0) {
          this.pagination.total = res.data.fileList.length;
        }
      });
    },
    getOptions() {
      return new Promise((resolve) => {
        getTreeData({ AppId: this.appId, Status: 1 }).then((res) => {
          this.categoryTree = formatData(res.data);
          resolve();
        });
      });
    },
    handleNodeClick(data, node) {
      if (data.id !== null && data.id.length !== 0) {
        this.formData.classOneId = data.id;
        this.formData.classOneName = data.name;
        this.formData.classOneMarking = data.code;
      }
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
      this.$refs["formData1"].resetFields();
      this.$refs["formData2"].resetFields();
      this.$emit("update:readOnly", false);
      this.$emit("update:editId", "");
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      this.$refs.formData1.validate((valid1) => {
        this.$refs.formData2.validate((valid2) => {
          if (valid1 && valid2) {
            this.loading = true;
            this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
            if (this.formData.id <= 0) {
              // eslint-disable-next-line no-unused-vars
              const {
                id,
                productNum,
                morphologyCode,
                unitCode,
                storageConditionCode,
                status,
                isException,
                ...formData
              } = this.formData;
              create({
                ...formData,
                morphologyCode: morphologyCode.value,
                morphologyName: morphologyCode.name,
                unitCode: unitCode.value,
                unitName: unitCode.name,
                storageConditionCode: storageConditionCode.value,
                storageConditionName: storageConditionCode.name,
              })
                .then((res) => {
                  if (res.code === 200) {
                    this.closeDialog();
                  } else {
                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                });
            } else {
              update({
                ...this.formData,
                morphologyCode: this.formData.morphologyCode.value,
                morphologyName: this.formData.morphologyCode.name,
                unitCode: this.formData.unitCode.value,
                unitName: this.formData.unitCode.name,
                storageConditionCode: this.formData.storageConditionCode.value,
                storageConditionName: this.formData.storageConditionCode.name,
              })
                .then((res) => {
                  if (res.code === 200) {
                    this.closeDialog();
                  } else {
                    this.showValidateMsgCheck(res);
                  }
                  this.loading = false;
                })
                .catch(() => {
                  this.loading = false;
                });
            }
          } else {
            return false;
          }
        });
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("alias", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("productNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("classOneId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("classTwoId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("classTwoName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("classOneName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "manufacturerAddress",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("manufacturerName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "manufacturerMobile",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("casNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("morphologyName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("morphologyCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("specifications", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("unitCode", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("unitName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("netWeight", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("temperatureLower", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("temperatureUpper", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "warrantyPeriodUnit",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("humidnessLower", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("humidnessUpper", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("repertoryLower", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("repertoryUpper", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "hazardousCharacteristics",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("emergencyRescue", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("safetyProtection", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "storeageConditions",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("imageUrl", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("roughWeight", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("warrantyPeriod", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "storageConditionCode",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg(
          "storageConditionName",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("isException", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("createUserId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("createUserName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("updateUserId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("updateUserName", this.errorMsg, res.msg);
      }
    },
    // 上传文件
    choiseFile() {
      this.$refs["upload"].$refs["upload-inner"].handleClick();
    },
    handleRemove(file, fileList) {
      this.$emit("deleteFile", `${this.$base}${file.response.data}`);
    },
    // 图片上传完成
    uploadImg(file, fileList) {
      if (!file) return;
      if (this.imgList.length > 0) {
        this.$message.error("上传总数不超过1个！");
        if (this.imgList.length === 1) {
          this.imgList = this.imgList.splice(-1);
          this.showImg = true;
        } else {
          this.showImg = false;
        }
        return;
      }
      if (file.size > 5 * 1024 * 1024) {
        this.imgList = [];
        this.$message.error("文件大小超出5M，请重新上传！");
        if (this.imgList.length === 1) {
          this.showImg = true;
        } else {
          this.showImg = false;
        }
        return;
      }
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        this.showImg = true;
        this.imgList = fileList;
        // this.formData.imageUrl =
        //   res.data.protocol +
        //   "/" +
        //   res.data.fileDomain +
        //   "/" +
        //   res.data.fileBucket +
        //   "/" +
        //   res.data.filePath;
        this.formData.imageUrl = res.data.filePath;
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    removeImg(values) {
      this.formData.imageUrl = "";
      this.imgList = [];
    },
    // 文件上传完成
    uploadFile(file, fileList) {
      if (!file) return;
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error("文件大小超出10M，请重新上传！");
        return;
      }
      if (fileList.length > 10) {
        this.$message.error("上传总数不超过10个！");
        return;
      }
      this.pagination.total = fileList.length;
      const obj = {
        businessType: this.businessType,
        file: file.raw,
      };
      const form = formdataify(obj);
      this.Base.uploadFileInfo(form).then((res) => {
        var data = {
          id: 0, // 说明是新增,id>0 说明是已存在)
          fileSize: res.data.fileSize, // 文件大小
          fileFormat: res.data.fileName.substring(
            res.data.fileName.lastIndexOf(".")
          ), // 文件格式
          // fileUrl:
          //   res.data.protocol +
          //   "/" +
          //   res.data.fileDomain +
          //   "/" +
          //   res.data.fileBucket +
          //   "/" +
          //   res.data.filePath, // 存储地址
          fileUrl: res.data.filePath, // 存储地址
          fileName: res.data.newFileName, // 存储文件名
          originalName: res.data.fileName, // 原始文件名
        };
        this.fileList.push(data);
        this.formData.fileList = this.fileList;
      });
    },
    // 删除
    deletefile(index) {
      this.Helper.deleteConfirm(() => {
        this.formData.fileList.splice(index, 1);
        this.pagination.total = this.pagination.total - 1;
      });
    },
    // 切换页码
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getEntrustFileList();
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
      this.getEntrustFileList();
    },
    downloadfile(row) {
      GetStaticFileInfo(row.fileUrl, row.originalName);
      // const x = new window.XMLHttpRequest();
      // x.open("GET", row.fileUrl, true);
      // x.responseType = "blob";
      // x.onload = () => {
      //   const url = window.URL.createObjectURL(x.response);
      //   const a = document.createElement("a");
      //   a.href = url;
      //   a.download = row.originalName;
      //   a.click();
      // };
      // x.send();
      // console.log(row.originalName)
      // const link = document.createElement('a')
      // link.style.display = 'none'
      // link.download = row.originalName
      // link.download = row.originalName
      // link.href = row.fileUrl
      // document.body.appendChild(link)
      // link.click()
      // document.body.removeChild(link)
    },
  },
};
</script>
<style lang="scss">
.storage-product-edit-dialog {
  .el-collapse-item__content {
    .chioseFileDiv {
      width: 30%;
      display: inline-block;
      & > p {
        width: 90%;
        margin: 0 auto;
        margin-top: 20px;
      }
    }
    .chioseFileTable {
      width: 68%;
      display: inline-block;
    }
  }
  .el-divider-specail {
    background: transparent;
    .el-divider__text {
      font-weight: bold;
      font-size: 15px;
      left: -20px;
    }
    &.el-divider-top {
      margin-top: 60px;
    }
  }
  .el-collapse-item__header {
    font-weight: bold;
    font-size: 15px;
  }
}
</style>
